package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.ResourceDownload;
import com.lmt.entity.search.ResourceDownloadSearch;
import com.lmt.repository.ResourceDownloadRepository;
import com.lmt.service.ResourceDownloadService;
import com.lmt.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("ResourceDownloadServiceImpl")
public class ResourceDownloadServiceImpl extends BaseService implements ResourceDownloadService {

	private Logger logger = LoggerFactory.getLogger(ResourceDownloadServiceImpl.class);

	private final ResourceDownloadRepository resourceDownloadRepository;

	@Autowired
	public ResourceDownloadServiceImpl(ResourceDownloadRepository resourceDownloadRepository) {
		this.resourceDownloadRepository = resourceDownloadRepository;
	}

	@Override
	public ResultData save(ResourceDownload resourceDownload) {
		this.resourceDownloadRepository.save(resourceDownload);
		if (null == resourceDownload.getId()) {
			logger.error("下载记录保存失败，用户ID={}，资源ID={}。", resourceDownload.getUserId(), resourceDownload.getResourceId());
			return ResultUtil.newFail("下载记录保存失败");
		}
		return ResultUtil.newSuccess();
	}

	@Override
	public int getDownloadNum(String userId) {
		return this.resourceDownloadRepository.countByUserId(userId);
	}

	@Override
	public ResultData search(ResourceDownloadSearch resourceDownloadSearch) {
		StringBuffer sql = new StringBuffer();
		List<Object> parameters = new ArrayList<>();
		sql.append("SELECT rd.gmt_create AS gmtCreate, ");
		sql.append("r.designation AS resourceName, ");
		sql.append("cl.designation AS classify, ");
		sql.append("d.designation AS dissertation, ");
		sql.append("(SELECT CASE WHEN COUNT(co.id) >= 1 THEN '未收藏' ELSE '已收藏' END FROM collection AS co ");
		sql.append("WHERE co.obj_id = r.id) AS collected ");
		sql.append("FROM resource_download AS rd, resource AS r, classify AS cl, dissertation AS d ");
		sql.append("WHERE rd.resource_id = r.id AND r.classify_id = cl.id AND r.dissertation_id = d.id ");
		sql.append("AND rd.user_id = ? ");
		parameters.add(resourceDownloadSearch.getUserId());
		if (!StringUtils.isEmpty(resourceDownloadSearch.getDesignation())) {
			sql.append("AND r.designation LIKE ? ");
			parameters.add("%" + resourceDownloadSearch.getDesignation() + "%");
		}
		sql.append("ORDER BY rd.gmt_create DESC ");
		Map<String, Object> result = this.paginationSearch(sql, resourceDownloadSearch, parameters);
		return ResultUtil.newSuccess("下载记录查询成功", result);
	}
}
